from wsgiref.simple_server import make_server
from urls import url_patterns


# def login():
#     with open('login.html', 'rb') as f:
#         data = f.read()
#     return data
#
#
# def index():
#     with open('index.html', 'rb') as f:
#         data = f.read()
#     return data
#
#
# def favicon():
#     with open('favicon.ico', 'rb') as f:
#         data = f.read()
#     return data
#
#
# def reg():
#     with open('reg.html', 'rb') as f:
#         data = f.read()
#     return data
#
#
def application(environ, start_response):
    # 当前请求路径
    path = environ.get('PATH_INFO')
    print("PATH_INFO", path)

    start_response('200 OK', [('Content-Type', 'text/html')])

    # if path == '/favicon.ico':
    #     # return [b'hello favicon.ico']
    #     with open('favicon.ico', 'rb') as f:
    #         data = f.read()
    #     return [data]
    # elif path == '/login':
    #     # return [b'hello favicon.ico']
    #     with open('login.html', 'rb') as f:
    #         data = f.read()
    #     return [data]
    # elif path == '/index':
    #     # return [b'hello favicon.ico']
    #     with open('index.html', 'rb') as f:
    #         data = f.read()
    #     return [data]
    # return [b'<h1>Hello, Web!</h1>']

    # 方案2：
    # url_patterns = [
    #     ('/login', login),
    #     ('/reg', reg),
    #     ('/index', index),
    #     ('/favicon.ico', favicon)
    # ]

    func = None
    for item in url_patterns:
        if path == item[0]:
            func = item[1]
            break

    if func:
        return [func(environ)]
    else:
        return [b'404!']

    return [b'<h1>Hello, Web!</h1>']


httpd = make_server('', 8800, application)

print('Serving HTTP on port 8800...')
# 开始监听HTTP请求
httpd.serve_forever()
